#!/usr/bin/env node

const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const open = require('open');
const multer = require('multer');
const mime = require('mime-types');
const { createApp } = require('./scripts/create-app');
const { publishApp } = require('./scripts/publish-app');
const { buildApp } = require('./scripts/build-app');

// 设置环境变量
require('dotenv').config({ 
  path: path.resolve(process.cwd(), '.env'),
  override: true
});

// 创建 Express 应用
const app = express();
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || 'localhost';

// 版本号
const version = require('./package.json').version;

// 工作目录路径
const WORK_DIR = process.cwd();

// 确保必要的目录存在
const ensureDirs = () => {
  const dirs = ['apps', 'templates', 'build', 'releases', 'uploads'];
  dirs.forEach(dir => {
    fs.ensureDirSync(path.join(WORK_DIR, dir));
  });
};

// 设置上传目录
const upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      const uploadDir = path.join(WORK_DIR, 'uploads');
      fs.ensureDirSync(uploadDir);
      cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
      const ext = mime.extension(file.mimetype);
      const timestamp = Date.now();
      cb(null, `${timestamp}.${ext}`);
    }
  })
});

// 启用 CORS
app.use(cors());

// 解析 JSON 请求体
app.use(express.json());

// 静态文件
app.use(express.static(path.join(__dirname, 'public')));
app.use('/apps', express.static(path.join(WORK_DIR, 'apps')));
app.use('/templates', express.static(path.join(WORK_DIR, 'templates')));
app.use('/uploads', express.static(path.join(WORK_DIR, 'uploads')));

// 应用列表路由
app.get('/api/apps', (req, res) => {
  const appsDir = path.join(WORK_DIR, 'apps');
  fs.ensureDirSync(appsDir);
  
  const apps = fs.readdirSync(appsDir)
    .filter(app => fs.statSync(path.join(appsDir, app)).isDirectory())
    .map(app => {
      try {
        const configPath = path.join(appsDir, app, 'app.json');
        if (fs.existsSync(configPath)) {
          const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
          return { id: app, ...config };
        }
        return null;
      } catch (err) {
        console.error(`Error reading app ${app}:`, err);
        return null;
      }
    })
    .filter(Boolean);
  
  res.json({ success: true, data: apps });
});

// 应用详情路由
app.get('/api/apps/:id', (req, res) => {
  const appId = req.params.id;
  const appDir = path.join(WORK_DIR, 'apps', appId);
  
  if (!fs.existsSync(appDir)) {
    return res.status(404).json({ success: false, message: '应用不存在' });
  }
  
  try {
    const configPath = path.join(appDir, 'app.json');
    if (fs.existsSync(configPath)) {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
      res.json({ success: true, data: { id: appId, ...config } });
    } else {
      res.status(404).json({ success: false, message: '应用配置不存在' });
    }
  } catch (err) {
    console.error(`Error reading app ${appId}:`, err);
    res.status(500).json({ success: false, message: '读取应用配置失败' });
  }
});

// 创建应用路由
app.post('/api/apps/create', async (req, res) => {
  const { name, description, template } = req.body;
  
  if (!name) {
    return res.status(400).json({ success: false, message: '应用名称不能为空' });
  }
  
  try {
    const appId = await createApp(name, description, template);
    res.json({ success: true, data: { id: appId } });
  } catch (err) {
    console.error('Error creating app:', err);
    res.status(500).json({ success: false, message: err.message });
  }
});

// 构建应用路由
app.post('/api/apps/:id/build', async (req, res) => {
  const appId = req.params.id;
  
  try {
    const result = await buildApp(appId);
    res.json({ success: true, data: result });
  } catch (err) {
    console.error(`Error building app ${appId}:`, err);
    res.status(500).json({ success: false, message: err.message });
  }
});

// 发布应用路由
app.post('/api/apps/:id/publish', async (req, res) => {
  const appId = req.params.id;
  const { version, notes } = req.body;
  
  try {
    const result = await publishApp(appId, version, notes);
    res.json({ success: true, data: result });
  } catch (err) {
    console.error(`Error publishing app ${appId}:`, err);
    res.status(500).json({ success: false, message: err.message });
  }
});

// 上传图片
app.post('/api/upload/image', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ success: false, message: '没有上传文件' });
  }
  
  const filePath = req.file.path;
  const relativePath = path.relative(WORK_DIR, filePath).replace(/\\/g, '/');
  
  res.json({
    success: true,
    data: {
      url: `/${relativePath}`
    }
  });
});

// 模板列表路由
app.get('/api/templates', (req, res) => {
  const templatesDir = path.join(WORK_DIR, 'templates');
  fs.ensureDirSync(templatesDir);
  
  const templates = fs.readdirSync(templatesDir)
    .filter(template => fs.statSync(path.join(templatesDir, template)).isDirectory())
    .map(template => {
      try {
        const configPath = path.join(templatesDir, template, 'template.json');
        if (fs.existsSync(configPath)) {
          const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
          return { id: template, ...config };
        }
        return null;
      } catch (err) {
        console.error(`Error reading template ${template}:`, err);
        return null;
      }
    })
    .filter(Boolean);
  
  res.json({ success: true, data: templates });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({ success: false, message: '接口不存在' });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error('Server error:', err);
  res.status(500).json({ success: false, message: err.message || '服务器内部错误' });
});

// 启动服务器
const startServer = () => {
  // 确保目录存在
  ensureDirs();
  
  return new Promise((resolve, reject) => {
    const server = app.listen(PORT, () => {
      console.log(chalk.blue('='.repeat(50)));
      console.log(chalk.blue(`Simple Tools 开发服务器 v${version}`));
      console.log(chalk.blue('='.repeat(50)));
      console.log(chalk.green(`开发服务器已启动: http://${HOST}:${PORT}`));
      console.log(chalk.yellow('按 Ctrl+C 停止服务器'));
      
      // 自动打开浏览器
      if (process.env.OPEN_BROWSER !== 'false') {
        open(`http://${HOST}:${PORT}`);
      }
      
      resolve(server);
    });
    
    server.on('error', (err) => {
      if (err.code === 'EADDRINUSE') {
        console.error(chalk.red(`错误: 端口 ${PORT} 已被占用`));
        reject(new Error(`端口 ${PORT} 已被占用`));
      } else {
        console.error(chalk.red('服务器启动失败:'), err);
        reject(err);
      }
    });
  });
};

// 如果直接运行此文件
if (require.main === module) {
  startServer().catch(err => {
    console.error(chalk.red('服务器启动失败:'), err);
    process.exit(1);
  });
}

module.exports = {
  app,
  startServer
}; 